<?php
class Server {
  public static function create_order($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    require_once '../include/ecomutils.class.php';
    $out = 0;
    foreach ($req->__purchases as $itm) {
      if (EComUtils::check_stock($orm, $itm) == false) {
        $out = 1;
      }
    }
    if ($out == 1) {
      setcookie('cart', json_encode($req->__purchases), time() + (86400 * 1));
      echo '您的东西已经被人买走了，请返回购物车';
      return;
    }
    
    if ($req->first_name == '' || 
        $req->last_name == '' || 
        $req->address1 == '' || 
        $req->city == '' || 
        $req->country == '' || 
        $req->zip == '' || 
        $req->phone == '' || 
        $req->email == '' ) {
      echo '送货地址不完整';
      return;
    }
    
    $req->date = date('Y-m-d', time());
    $req->order_number = date('YmdHis', time());
    $orm->add('pb_ecom_order', $req);
    $req->id = $orm->last_id();
    if (isset($req->__newaddr)) {
      if (isset($_SESSION['user'])) {
        $orm->add('pb_ecom_customer_addr', $req->__newaddr);
        $req->__newaddr->id = $orm->last_id();
        
        $user = json_decode($_SESSION['user']);
        $user->__addrs[] = $req->__newaddr;
        $_SESSION['user']= json_encode($user);
        
        unset($req->__newaddr);
      }
    }
    
    
    foreach ($req->__purchases as $itm) {
      $itm->order_id = $req->id;
      $itm->customer_id = $req->customer_id;
      $orm->add('pb_ecom_purchase', $itm);
      EComUtils::update_stock($orm, $itm, 0);
    }
    
    unset($_SESSION['cart']);
    
    if (!isset($_SESSION['profile'])) {
      $rslt = $orm->get('pb_ecom_admin', NULL, NULL, NULL, NULL, NULL)->d;
      if (count($rslt) > 0) {
        $_SESSION['profile'] = $rslt[0];
      }
    }
    
    $req->__shop = $_SESSION['profile']->shop_name;
    try {
      $postdata = http_build_query(
        array(
          'od' => json_encode($req)
        )
      );
      $opts = array('http' =>
        array(
          'method'  => 'POST',
          'header'  => 'Content-type: application/x-www-form-urlencoded',
          'content' => $postdata
        )
      );
      $context  = stream_context_create($opts);
      $content = file_get_contents(URL . HOME_DIR . '__odcn.php', true, $context);
      
//      $tmpfile = TMP_DIR . "$req->order_number.pdf";
//      require_once '../3rd_party/MPDF56/mpdf.php';
//      $mpdf = new mPDF('c'); 
//      $mpdf->SetDisplayMode('fullpage');
//      // LOAD a stylesheet
//      $stylesheet = "
//      <html>
//      <head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>
//      <body>$content</body>
//      </html>
//      ";
//      $mpdf->WriteHTML($stylesheet);
//      $mpdf->Output($tmpfile);
      
      require_once '../3rd_party/phpMailer/class.phpmailer.php';
      $mailer = new PHPMailer();
      $mailer->IsSMTP();
      $mailer->Host = SMTP_HOST;
      $mailer->CharSet = "UTF-8";
      
      $mailer->SMTPAuth = true;
      $mailer->Username = SMTP_USER_ATDN;
      $mailer->Password = SMTP_PASS_ATDN;
      $mailer->From = $_SESSION['profile']->email;
      $mailer->FromName = $_SESSION['profile']->shop_name;
      
      $mailer->Body = $content;
      $mailer->Subject = 'Order #' . $req->order_number;
    
      $mailer->isHTML(true);
      $mailer->AddAddress($req->email, '');
      $mailer->Send();
//      $mailer->AddAttachment($tmpfile);
    
    } catch (phpmailerException $e) {
      echo $e->errorMessage(); //Pretty error messages from PHPMailer
    } catch (Exception $e) {
      echo $e->getMessage(); //Boring error messages from anything else!
    }
    
    unset($req->__purchases);
    
    echo json_encode($req);
  }
  
  public static function delete_addr($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    $orm->delete('pb_ecom_customer_addr', $req);

    if (isset($_SESSION['user'])) {
      $user = json_decode($_SESSION['user']);
      foreach ($user->__addrs as $idx => $itm) {
        if ($itm->id == $req->id) {
          array_splice($user->__addrs, $idx, 1);
        }
      }
      
      if ($req->is_default == 1) {
        $opts = new stdClass();
        $opts->cd = 't.customer_id = :v1';
        $opts->cdv = array(':v1' => $req->customer_id);
        $rslt = $orm->get('pb_ecom_customer_addr', NULL, NULL, NULL, NULL, $opts)->d;
        if (count($rslt) > 0) {
          $rslt[0]->is_default = 1;
          $orm->update('pb_ecom_customer_addr', $rslt[0]);
        }
      }
      
      $_SESSION['user']= json_encode($user);
    }
  }
  
  public static function update_addr($orm, $sys, $inst, $is_iframe) {
    $req = json_decode(Utils::get_param('req', '[]'));
    $orm->update('pb_ecom_customer_addr', $req);

    if (isset($_SESSION['user'])) {
      $user = json_decode($_SESSION['user']);
      foreach ($user->__addrs as $idx => $itm) {
        if ($itm->id == $req->id) {
          $user->__addrs[$idx] = $req;
        }
      }
      
      $_SESSION['user']= json_encode($user);
    }
  }
}
?>